import { defineStore } from 'pinia'
import { ref, computed, readonly } from 'vue'
import type { User, LoginRequest, RegisterRequest } from '@/types/auth'
import * as authApi from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const accessToken = ref<string | null>(null)
  const isLoading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!accessToken.value && !!user.value)

  // 初始化 - 从localStorage恢复状态
  const initAuth = () => {
    const token = localStorage.getItem('accessToken')
    const userData = localStorage.getItem('user')
    
    if (token && userData) {
      accessToken.value = token
      try {
        user.value = JSON.parse(userData)
      } catch (error) {
        console.error('Failed to parse user data:', error)
        clearAuth()
      }
    }
  }

  // 登录
  const login = async (credentials: LoginRequest) => {
    try {
      isLoading.value = true
      const response = await authApi.login(credentials)
      
      if (response.success && response.data) {
        const { user: userData, accessToken: token } = response.data
        
        // 更新状态
        user.value = userData
        accessToken.value = token
        
        // 持久化到localStorage
        localStorage.setItem('accessToken', token)
        localStorage.setItem('user', JSON.stringify(userData))
        
        return { success: true }
      } else {
        throw new Error(response.message || '登录失败')
      }
    } catch (error) {
      console.error('Login error:', error)
      return { 
        success: false, 
        message: error instanceof Error ? error.message : '登录失败' 
      }
    } finally {
      isLoading.value = false
    }
  }

  // 注册
  const register = async (userData: RegisterRequest) => {
    try {
      isLoading.value = true
      const response = await authApi.register(userData)
      
      if (response.success && response.data) {
        const { user: newUser, accessToken: token } = response.data
        
        // 更新状态
        user.value = newUser
        accessToken.value = token
        
        // 持久化到localStorage
        localStorage.setItem('accessToken', token)
        localStorage.setItem('user', JSON.stringify(newUser))
        
        return { success: true }
      } else {
        throw new Error(response.message || '注册失败')
      }
    } catch (error) {
      console.error('Register error:', error)
      return { 
        success: false, 
        message: error instanceof Error ? error.message : '注册失败' 
      }
    } finally {
      isLoading.value = false
    }
  }

  // 登出
  const logout = () => {
    clearAuth()
  }

  // 清除认证信息
  const clearAuth = () => {
    user.value = null
    accessToken.value = null
    localStorage.removeItem('accessToken')
    localStorage.removeItem('user')
  }

  // 更新用户资料
  const updateProfile = async (profileData: Partial<User>) => {
    try {
      isLoading.value = true
      const response = await authApi.updateProfile(profileData)
      
      if (response.success && response.data) {
        user.value = response.data
        localStorage.setItem('user', JSON.stringify(response.data))
        return { success: true }
      } else {
        throw new Error(response.message || '更新失败')
      }
    } catch (error) {
      console.error('Update profile error:', error)
      return { 
        success: false, 
        message: error instanceof Error ? error.message : '更新失败' 
      }
    } finally {
      isLoading.value = false
    }
  }

  // 验证token有效性
  const verifyToken = async () => {
    if (!accessToken.value) return false
    
    try {
      const response = await authApi.verifyToken()
      return response.success
    } catch (error) {
      console.error('Token verification failed:', error)
      clearAuth()
      return false
    }
  }

  return {
    // 状态
    user: readonly(user),
    accessToken: readonly(accessToken),
    isLoading: readonly(isLoading),
    
    // 计算属性
    isAuthenticated,
    
    // 方法
    initAuth,
    login,
    register,
    logout,
    updateProfile,
    verifyToken
  }
})